var mainCustomerId=sessionStorage.getItem("mainCustomerId");
var isOrSigndt='';
var isaccountRole =[];//设置为管理员的
$("#mainCustomerName").html(window.sessionStorage.getItem('mainCustomerName'));

mainCustomerInfo();
//账号创建
function accountcreation() {
    $.ajax({
        url:root.member.addMembers,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "loginAccount":$("#loginAccount").val(),
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "mainCustomerId":mainCustomerId,
        }),
        success: function (data) {
            if (data.errorCode==0){
                $.Huimodalalert("创建成功",2000);
                $("#loginAccount").val("")
                accountquery()
            } else {
                $.Huimodalalert(data.msg,2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//账号查询
getAdnAntByMnuomerIdfn()
function getAdnAntByMnuomerIdfn(){
    $.ajax({
        url:urldt= root.member.getAdminAccountByMainCustomerId+"?mainCustomerId="+mainCustomerId,
        cache: false, //禁用缓存
        type: "POST",
        success: function (data) {
            if(data.errorCode==0){
             if(data.data != null){
                 for (var i=0;0<data.data.length;i++){
                     isaccountRole.push(data.data[i].memberId)
                 }

             }else{
                isaccountRole  =[]
             }
            }else {
                $.Huimodalalert(data.msg,2000);

            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
      });
}
accountquery()
function accountquery() {
    $.ajax({
        url:root.member.getMembers,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":30,
            "loginAccount":$("#accountloginaccount").val(),
            "mobilePhone":$("#accountmobilePhone").val(),
            "employUser":$("#accountemployUser").val(),
            "status":$("#accountstatus").val(),
            "mainCustomerId":mainCustomerId,
        }),
        success: function (data) {
            accountcouponlist(data.data, 0);
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.member.getMembers,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":30,
                            "loginAccount":$("#accountloginaccount").val(),
                            "mobilePhone":$("#accountmobilePhone").val(),
                            "employUser":$("#accountemployUser").val(),
                            "status":$("#accountstatus").val(),
                            "mainCustomerId":mainCustomerId,

                        }),
                        success: function (result) {
                            accountcouponlist(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
var dataSource = new Array();
var table;   //table对象
dataSource = [];
function accountcouponlist(data, index){
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data.data));
    dataSource.splice(0,dataSource.length);//清空数组
    if(data.data !=null && data.data != ''){
        var datashu =data.startRow+1;
        $.each(data.data, function (i, field) {
            var datashus = datashu++
            var rowData = new Array();

            rowData.push(field.loginAccount);
            rowData.push(field.mobilePhone);
            rowData.push(field.status);
            rowData.push(field.registerTime);
            rowData.push(field.createUser);
            rowData.push(field.employUser );
            rowData.push(datashus);
            rowData.push(field.memberId);
            rowData.push(field.isRelationCustomer);
            rowData.push(field.accountRole);//账号角色 10：管理员
            rowData.push(field.email);//邮箱
            dataSource.push(rowData);

        });
    }
    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#accountdatatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#accountdatatable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0];
                        var account ='';
                        if (val == undefined) {
                            val = ''
                        }
                        if(row[9] == 10){
                            account ='管理员'
                        }else{
                            account ='' 
                        }
                        return account + val;
                    },
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[1] == "" || row[1] == null) {
                            val = row[1]
                        }else {
                            val = '<span>'+row[1] +'</span><input name="" type="button" onclick="updatamobile(\'' + row[0] + '\',\'' + row[1] + '\',\'' + row[7] + '\')"   class="btn  radius size-S ml-10 powerButton 600" value="编辑">'
                        }
                        return val;
                    },
                    "targets": 1
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[5] == undefined) {
                            val = ' <input name="" onclick="editUser(\'' + row[7] + '\',\'' + row[5] + '\')" type="button" class="btn  radius size-S" value="编辑">'
                        }else {
                            val = '<span>'+row[5]+'</span>&nbsp;<input name="" type="button" onclick="editUser(\'' + row[7] + '\',\'' + row[5] + '\')"  class="btn  radius size-S powerButton 600" value="编辑">'
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[10] == undefined) {
                            val = ' <input name="" onclick="editemail(\'' + row[7] + '\',\'' + row[10] + '\')" type="button" class="btn  radius size-S" value="编辑">'
                        }else {
                            val = '<span>'+row[10]+'</span>&nbsp;<input name="" type="button" onclick="editemail(\'' + row[7] + '\',\'' + row[10] + '\')"  class="btn  radius size-S powerButton 600" value="编辑">'
                        }
                        return val;
                 
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val=""
                        if(row[2]==10){
                            val = '<span class="dropDown"> <a class="dropDown_A" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">开启<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow"><li onclick="accountstart(\'' + 1 + '\',\'' + row[7] + '\')"><a href="#">关闭</a></li></ul></span>';

                        }else {
                            val = '<span class="dropDown"> <a class="dropDown_A" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">关闭<i class="Hui-iconfont">&#xe6df;</i></a><ul class="dropDown-menu menu radius box-shadow"><li onclick="accountstart(\'' + 2 + '\',\'' + row[7] + '\')"><a href="#">开启</a></li></ul></span>';

                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 6
                },

                {
                    "render": function (data, type, row, meta) {
                        var val=""
                        if(row[8]==false){
                            if(row[9] == 10){
                                var SetAdminRole=''
                                if(isaccountRole!=""){
                                    for(var i=0;i<isaccountRole.length;i++){
                                        if(row[7] == isaccountRole[i]){
                                            SetAdminRole='<span class="powerButton 581"><a class="setadmie" setadmiedata="' + row[7] + '" onclick="setupdateSetAdminRole(\'' + row[7] + '\',2)">取消管理员</a></span>'

                                        }
                                    }

                                }
                                val = '<span class="powerButton 581"><a onclick="resetPassword(\'' + row[0] + '\')">重置密码</a></span><span class="ml-10 powerButton 601"><a onclick="accountCancellation(\'' + row[7] + '\',\'' + row[0] + '\')">注销</a></span>&nbsp&nbsp'+SetAdminRole+''
                            }else{
                                val = '<span class="powerButton 581"><a onclick="resetPassword(\'' + row[0] + '\')">重置密码</a></span><span class="ml-10 powerButton 601"><a onclick="accountCancellation(\'' + row[7] + '\',\'' + row[0] + '\')">注销</a></span>&nbsp&nbsp<span class="powerButton 581"><a  class="setadmie"  setadmiedata="' + row[7] + '" onclick="setupdateSetAdminRole(\'' + row[7] + '\',1)">设为管理员</a></span>'
                            }

                        }else {
                   
                            if(row[9] == 10){
                                var SetAdminRole2=''
                                if(isaccountRole!=""){
                                    for(var i=0;i<isaccountRole.length;i++){
                                        if(row[7] == isaccountRole[i]){
                                            SetAdminRole2='<span class="powerButton 581"><a class="setadmie" setadmiedata="' + row[7] + '" onclick="setupdateSetAdminRole(\'' + row[7] + '\',2)">取消管理员</a></span>'

                                        }
                                    }

                                }
                                val = '<span class="powerButton 581"><a onclick="resetPassword(\'' + row[0] + '\')">重置密码</a></span>&nbsp&nbsp'+SetAdminRole2+''
                            }else{
                                val = '<span class="powerButton 581"><a onclick="resetPassword(\'' + row[0] + '\')">重置密码</a></span>&nbsp&nbsp<span class="powerButton 581"><a class="setadmie" setadmiedata="' + row[7] + '"  onclick="setupdateSetAdminRole(\'' + row[7] + '\',1)">设为管理员</a></span>'
                            }

                        }
                        return val;
                    },
                    "targets": 7
                },



            ]
        });
        //权限控制函数
        power()
    };
}

//设为管理员
function setupdateSetAdminRole(id,num){
    var urldt='';
    if(num == 2){//取消
        urldt=root.member.updateCancelAdminRole+"?memberId="+id
       
    }else{//设置
        urldt= root.member.updateSetAdminRole+"?memberId="+id
    
    }
    $.ajax({
        url:urldt,
        cache: false, //禁用缓存
        type: "POST",
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('成功',2000);
                getAdnAntByMnuomerIdfn()
                accountquery();
            }else {
                $.Huimodalalert(data.msg,2000);

            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
      });

}
//注销账号
function accountCancellation(id,names) {
    var curInd = layer.confirm('<span id="status" style="width:200px;height:100px;resize: none;" maxlength="200" >注销后，账号将被清除不可恢复！确定要注销账号?</span>', {title:'提示',btn: ['确定', '取消']}, function(index){
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            url:root.member.cancelAccount,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            data: JSON.stringify({
                "member_id":id,
                "login_account":names,
            }),
            success: function (data) {
                if(data.errorCode==0){
                    $.Huimodalalert('注销成功！',2000);
                    getAdnAntByMnuomerIdfn()
                    accountquery();
                }else {
                    $.Huimodalalert(data.msg,2000);

                }
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })
        layer.close(curInd);
    },function(){
        layer.close(curInd);

    });

}
//修改手机号
function updatamobile(name,phoneNumber,id) {
    var curInd = layer.confirm(
        '<span>账号：</span><span>'+name+'</span><br><span>手机号：</span><input  onkeyup="limits()" id="phoneNumber" maxlength="11"  autocomplete="off" placeholder="" value="'+phoneNumber+'">'+'<br/>', {title:'修改手机号',btn: ['确定', '取消']}, function(index){
            if($("#phoneNumber").val()==""){
                showMsg(5, '手机号不可为空！');
                return false;
            }
            $.ajax({
                contentType: "application/json;charset=UTF-8",
                url:root.member.updateMobilePhone,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                data: JSON.stringify({
                    "member_id":id,
                    "mobile_phone":$("#phoneNumber").val(),

                }),
                success: function (data) {
                    if(data.errorCode==0){
                        $.Huimodalalert('修改成功！',2000);
                        accountquery();
                    }else {
                        $.Huimodalalert(data.msg,2000);

                    }
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            })
            layer.close(curInd);

        },function(){
            layer.close(curInd);

        });
}
//限制手机号
function limits() {
    if($("#phoneNumber").val()!=""){
        var value=$("#phoneNumber").val()
        var reg=/^[1-9]\d*$|^0$/;
        if(reg.test(value)!=true){
            showMsg(5, '手机号格式有误！');
        }
    }

}
//修改状态
function accountstart(val,memberId) {
    var wenan=""
    var statuss=""
    if(val==1){
        wenan="确定要关闭吗？"
        statuss=20
    }else {
        wenan="确定要开启吗？"
        statuss=10
    }
    var curInd = layer.confirm(
        '<span>'+wenan+'</span>'+'<br/>', {title:'提示',btn: ['确定', '取消']}, function(index){
            $.ajax({
                url:root.member.updateMemberStatus2,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify({
                    "memberId":memberId,
                    "optUserId":"1",
                    "optUserName":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                    "status":statuss
                }),
                success: function (data) {
                    if(data.errorCode==0){
                        accountquery()
                    }else {
                        $.Huimodalalert(data.msg,2000);
                    }
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });
            layer.close(curInd);

        },function(){
            layer.close(curInd);

        });
}

//弹框
function showMsg(icon, msg) {
    layer.msg(msg, {
        icon: icon,
        time: 1000
    });
}
//编辑使用人
function editUser(memberId,name) {
    var curInd = layer.confirm(
        '<span>使用人：</span><input  id="user" maxlength="10" autocomplete="off" placeholder="请输入使用人"  value='+name+'>'+'<br/>', {title:'添加使用人',btn: ['确定', '取消']}, function(index){

            $.ajax({
                url:root.member.updateMemberEmploy,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify({
                    "memberId":memberId,
                    "employUser":$("#user").val(),
                    "mainCustomerId":mainCustomerId,
                }),
                success: function (data) {
                    if(data.errorCode==0){
                        accountquery()
                    }else {
                        $.Huimodalalert(data.msg,2000);
                    }
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });
            layer.close(curInd);

        },function(){
            layer.close(curInd);

        });
}
function showMsg(icon, msg) {
    layer.msg(msg, {
        icon: icon,
        time: 1000
    });
}
//编辑邮箱
function editemail(id,emaildt){
    var curInd = layer.confirm(
        '<span>邮箱：</span><input  id="email"  autocomplete="off" placeholder="请输入邮箱" maxlength="50" value='+emaildt+'> '+'<br/>', {title:'添加邮箱',btn: ['确定', '取消']}, function(index){
            if($("#email").val() != ""){
                if($("#email").val().indexOf('@')== -1 || $("#email").val().indexOf('.')== -1){
                    showMsg(5, '邮箱格式不正确');
                    return 
                }else{
                    $.ajax({
                        url: root.member.updateEmail+"?memberId="+id+'&email='+$("#email").val(),
                        cache: false, //禁用缓存
                        type: "POST",
                        success: function (data) {
                            if(data.errorCode==0){
                                $.Huimodalalert('修改成功',2000);
                                layer.close(curInd);
                                accountquery()
                            }else {
                                $.Huimodalalert(data.msg,2000);
                            }
                        }
                      });  
                }
            }else{
            $.ajax({
                url: root.member.updateEmail+"?memberId="+id+'&email='+$("#email").val(),
                cache: false, //禁用缓存
                type: "POST",
                success: function (data) {
                    if(data.errorCode==0){
                        $.Huimodalalert('修改成功',2000);
                        layer.close(curInd);
                        accountquery()
                    }else {
                        $.Huimodalalert(data.msg,2000);
                    }
                }
              });
          
        }

        },function(){
            layer.close(curInd);

        });
}
//重置密码
function resetPassword(loginAccounts) {
    var curInd = layer.confirm('<span>确定要重置密码吗？</span>'+'<br/>', {title:'重置密码',btn: ['确定', '取消']}, function(index){

            $.ajax({
                url:root.member.resetPassword,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify({
                    "loginAccount":loginAccounts,
                    "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                    "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                }),
                success: function (data) {
                    if(data.errorCode==0){
                        $.Huimodalalert('重置成功',2000);
                        accountquery()
                    }else {
                        $.Huimodalalert(data.msg,2000);
                    }
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            })
            layer.close(curInd);

        },function(){
            layer.close(curInd);

        });
}
/*-------------------------------------------------------------华丽丽的分割线-----------------------------------------------------------------------------*/


//账号关联
//选择项目
function selectitem() {

    $.ajax({
        url:root.member.getCustomerDropDown,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "mainCustomerId":mainCustomerId,
            "customerName":$("#selectitem").val()
        }),
        success: function (data) {
            if(data.errorCode=="0"){
                var jsonObj =data.data;
                $("#tuank2").html("");
                if(jsonObj==""){
                    $("#tuank2").html("<li>无数据</li> ");
                }else {
                    var optionstring = "";
                    for (var  i= 0; i < jsonObj.length; i++) {
                        optionstring += "<li class='dda' onclick='relation2(\""+ jsonObj[i].customerId+"\",\""+jsonObj[i].customerName+"\")' data-align=\"" + jsonObj[i].customerId + "\" > " + jsonObj[i].customerName + "</li>";
                    }
                    $("#tuank2").html(optionstring);
                    $("#tuank2").show()


                }
            }else{
                $("#tuank2").html("<li>无数据</li> ");
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });

}
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuank2").length == 0 && $(e.target).closest("#selectitem").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuank2").hide()
    }
})
function relation2(id,ce) {
    $("#selectitem").val(ce).text(id)
    $("#tuank2").hide()
}
var orderaccountarr=[]//下单账号
var orderaccount={}
var settlementaccountarr=[]//结算账号
var settlementaccount={}
var approvalaccountarr=[]//审批账号
var approvalaccount={}

//账号
myFunctionaa()
function myFunctionaa(){
    $.ajax({
        url:root.member.getMembers,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":5000,
            "loginAccount":$("#organization_name").val(),
            "mobilePhone":"",
            "employUser":"",
            "status":"10",
            "mainCustomerId":mainCustomerId,
        }),
        success: function (data) {
            if(data.errorCode=="0"){
                var jsonObj =data.data.data;
                $("#tuankd").html("");
                if(jsonObj==""){
                    $("#tuankd").html("<li>无数据</li> ");
                }else {
                    var optionstring = "";
                    for (var  i= 0; i < jsonObj.length; i++) {
                        optionstring += "<li class='dda' onclick='relationd("+ jsonObj[i].memberId+",\""+jsonObj[i].loginAccount+"\")' data-align=\"" + jsonObj[i].memberId + "\" > " + jsonObj[i].loginAccount + "</li>";                    }
                    $("#tuankd").html(optionstring);
                    $(".kehus").animate({scrollTop:"0"},1);
                    $("#tuankd").show()


                }
            }else{
                $("#tuankd").html("<li>无数据</li> ");
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
    /*setadminfn();*/
}
/*function setadminfn(){
    //判断初始化 显示设置管理员按钮 操作(列表上没有10 显示所有的 设为管理员 按钮 ，列表上有一个10 其他的设为管理员 按钮不显示)
var setadmieli= $("#accountdatatable").find('.setadmie');
var setadminlist=[];
        for(var f=0;f<$(setadmieli).length;f++){
        console.log($(setadmieli))
/!*
        console.log($(item).attr('setadmiedata'))
*!/
            if(isaccountRole!=""){

                for(var i=0;i<isaccountRole.length;i++){
                    if( $(item).attr('setadmiedata') == isaccountRole[i]){
                        console.log( $(item.html()))
                        $(item).html('取消管理员')

                    }else{
                        $(item).html('设为管理员')
                    }
                }

            }else{
                    $(item).html('设为管理员')
                
            }     
        
    }
}*/
function relationd(id,ce) {
    $("#organization_name").val(ce).text(id)
    $("#tuankd").show()
}
var approvalorders=0//审批顺序交互
function orderaccountadd(val){
    if(val==1){
        //下单账号添加
        //赋值
        console.log($("#organization_name").text())
        console.log($("#organization_name").val())
        if($("#organization_name").text()!=""&&$("#organization_name").val()!="") {
            $("#orderaccountadd").html($("#organization_name").val())
            orderaccount = {
                "memberId": $("#organization_name").text()
            }
            orderaccountarr.push(orderaccount)
            //改变高亮显示
            $("#adds").removeClass("add-one")
            $("#deletes").removeClass("delete-one")
            $("#adds").addClass("add2-one")
            $("#deletes").addClass("delete2-one")
            $("#adds").removeAttr("onclick");
            $("#deletes").attr("onclick", "orderaccountdelete(1)")
            $("#organization_name").val("")
            $("#organization_name").text("")
        }else {
            $.Huimodalalert('请选择账号！',2000);
        }
    }else if (val==2) {
       //审批账号添加
        if($("#organization_name").text()!=""&&$("#organization_name").val()!=""){
            $("#deletes2").removeClass("delete-one")
            $("#deletes2").addClass("delete2-one")
            $("#deletes2").attr("onclick","orderaccountdelete(2)")

            approvalaccount={
                "memberId":$("#organization_name").text(),
            }
            //去重
            for (let j=0;j<approvalaccountarr.length;j++) {
                if ($("#organization_name").text() == approvalaccountarr[j].memberId){
                    $.Huimodalalert('不能添加重复数据！',2000);
                    return false;
                }
            }
            approvalaccountarr.push(approvalaccount)
                if(approvalaccountarr.length>19){
                    $("#adds2").removeClass("add-one")
                    $("#adds2").addClass("add2-one")
                    $("#adds2").removeAttr("onclick");
                }

            var approvalhtml=""
            if(approvalorders==0){
                if($("#civil").is(':checked')==true){
                    approvalhtml='<span>审批顺序</span><input type="text" id="approvalinput" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony hide"><span>订单金额</span>< <span><input  class="motyval" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
                }else {
                    approvalhtml='<span class="approval-orderxu">--</span>' 
                }
            }else {
                approvalhtml='<span>审批顺序</span><input type="text" id="approvalinput" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony hide"><span>订单金额</span>< <span><input  class="motyval"  style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
            }
            var approvalaccounts= '';
            approvalaccounts+=' <li class="every-approval">' +
                '<input class="checkbox selection" onclick="accountid(this)" type="checkbox" value='+$("#organization_name").text()+'></span>' +
                ' <span class=" accountnumber">'+$("#organization_name").val()+'</span><span class=" accountnumber2" style="display: none">'+$("#organization_name").text()+'</span>' +
                '<span class="approvalorder">'+approvalhtml+'</span>' +

                '</li>'

            $(".approvalaccounts").append(approvalaccounts)


            $("#organization_name").val("")
            $("#organization_name").text("")

        }else {
            $.Huimodalalert('请选择账号！',2000);
        }


    }else if (val==3){
        //结算账号添加
        //赋值
        if($("#organization_name").text()!=""&&$("#organization_name").val()!="") {
            $("#settlementaccount").html($("#organization_name").val())
            settlementaccount = {
                "memberId": $("#organization_name").text(),
            }
            settlementaccountarr.push(settlementaccount)
            //改变高亮显示
            $("#adds3").removeClass("add-one")
            $("#deletes3").removeClass("delete-one")
            $("#adds3").addClass("add2-one")
            $("#deletes3").addClass("delete2-one")
            $("#adds3").removeAttr("onclick");
            $("#deletes3").attr("onclick", "orderaccountdelete(3)")
            $("#organization_name").val("")
            $("#organization_name").text("")
        }else {
            $.Huimodalalert('请选择账号！',2000);
        }
    }


}

//改变审批顺序下样式
function xuanzhonga() {
    var approvalorder= $(".approvalorder");
    var ordermony=$(".ordermony");
    var isapprovalorder =$(".isapprovalorder");
    var approvalli=$("#menu li")
    for (let i=0;i<approvalli.length;i++) {
        console.log($("#civil").is(':checked'))
        if($("#civil").is(':checked')==true){
            approvalorders=1
            isOrSigndt = 0
            $(approvalorder[i]).html('<span>审批顺序</span><input type="text" id="approvalinput"  class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber"  onclick="showhdemoy(this)" type="checkbox" name="scene" ></span><span  class="ordermony hide"><span>订单金额</span>< <span><input  class="motyval" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>')

        }else {
            approvalorders=0
            isOrSigndt = ''
            $(approvalorder[i]).html('<span class="approval-orderxu">--</span>')
            $(ordermony[i]).html('<span class="approval-orderxu">--</span>')
            $(isapprovalorder[i]).html('<span class="approval-orderxu">--</span>')

        }
    }


}
function huoqianfn(){
    var approvalorder= $(".approvalorder");
    var ordermony=$(".ordermony");
    var isapprovalorder =$(".isapprovalorder");
    var approvalli=$("#menu li") 
    for (let i=0;i<approvalli.length;i++) {
        console.log($("#huoqian").is(':checked'))
        if($("#huoqian").is(':checked')==true){
            isOrSigndt = 1
            $(approvalorder[i]).html('<span class="approval-orderxu">--</span>')
            $(ordermony[i]).html('<span class="approval-orderxu">--</span>')
            $(isapprovalorder[i]).html('<span class="approval-orderxu">--</span>')
        }else {
            isOrSigndt = ''
            $(approvalorder[i]).html('<span>审批顺序</span><input type="text" id="approvalinput"  class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" onclick="showhdemoy(this)" type="checkbox" name="scene" ></span><span  class="ordermony"><span>订单金额</span>< <span><input  class="motyval"  style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>')

        }
    }  
}
//选中数据组成的数组
var accountids={}
var accountmemberId=[]//只用
//获取选中的val
var xuanzhongval={}
var xuanzhongaccount=[]
function accountid(k) {
    if($(k).is(':checked')==true){
        console.log(k)
        //点击勾选的数据保存
        accountids={
            "accountindex":k
        }
        //获取选中的val
        xuanzhongval={
            "accountval":$(k).val()
        }
        //选中时去重
       /* for (let j=0;j<xuanzhongaccount.length;j++) {
            if ($(k).val() == xuanzhongaccount[j].accountval){
                return false;
            }
        }*/
        accountmemberId.push(accountids)//点击勾选的数据保存
        xuanzhongaccount.push(xuanzhongval)//获取选中的val
    }else {
        //选中取消时去重
        for (let j=0;j<xuanzhongaccount.length;j++) {
            if ($(k).val() == xuanzhongaccount[j].accountval) {
                xuanzhongaccount.splice(j,1)
            }

        }
        for (let i=0;i<accountmemberId.length;i++) {
            if ($(k).val() == $(accountmemberId[i].accountindex).val()) {
                accountmemberId.splice(i,1)
            }
        }

    }
    console.log(accountmemberId)
}
//删除按钮
function orderaccountdelete(val){
    if(val==1){
        //下单账号删除
        //删除值
        $("#orderaccountadd").html("")
        orderaccountarr.splice(orderaccountarr[0])
        //改变高亮显示
        $("#adds").removeClass("add2-one")
        $("#deletes").removeClass("delete2-one")
        $("#adds").addClass("add-one")
        $("#deletes").addClass("delete-one")
        $("#adds").attr("onclick","orderaccountadd(1)")
        $("#deletes").removeAttr("onclick");
    }else if (val==2) {
        //审批账号删除

                //清空选中数据数组
        for (let j=0;j<accountmemberId.length;j++) {
            for (let i=approvalaccountarr.length - 1;i >= 0;i--) {
                let memberId = approvalaccountarr[i].memberId;
                let memberId2 = $(accountmemberId[j].accountindex).val();
                if (memberId == memberId2){
                    approvalaccountarr.splice(i,1);
                    $(accountmemberId[j].accountindex).parent().remove()
                }

            }
        }
        accountmemberId.splice(0,accountmemberId.length)
        //改变高亮
        var approvalli=$("#menu li")
        if(approvalli.length==0){
            $("#adds2").removeClass("add2-one")
            $("#deletes2").removeClass("delete2-one")
            $("#adds2").addClass("add-one")
            $("#deletes2").addClass("delete-one")
            $("#adds2").attr("onclick","orderaccountadd(2)")
            $("#deletes2").removeAttr("onclick");
        }else {
            $("#adds2").removeClass("add2-one")
            $("#adds2").addClass("add-one")
            $("#adds2").attr("onclick","orderaccountadd(2)")
        }

    }else if (val==3){
        //结算账号删除
        //删除值
        $("#settlementaccount").html("")
        settlementaccountarr.splice(settlementaccountarr[0])
        //改变高亮显示
        //改变高亮显示
        $("#adds3").removeClass("add2-one")
        $("#deletes3").removeClass("delete2-one")
        $("#adds3").addClass("add-one")
        $("#deletes3").addClass("delete-one")
        $("#adds3").attr("onclick","orderaccountadd(3)")
        $("#deletes3").removeAttr("onclick");
    }
}
/*防止重复提交  10秒后恢复*/
var isSubmitClick = true;
$('.input_button_blue').click(function () {
    if (isSubmitClick) {
        isSubmitClick = false;
        $('.input_button_blue').css("background-color", "red");
        // $("form:first").submit();//提交第一个表单
        $("form[name='form_month']").submit();
        setTimeout(function () {
            $('.input_button_blue').css("background-color", "#3CBAFF");
            isSubmitClick = true;
        }, 10000);
    }
});
//建立关联
//审批顺序用的数组
var llmap=[]
var newarr=[];
var countnew=[];
var isIng = false;
function establishingcorrelation(){
    newarr=[];
    countnew=[];
    llmap=[];
    if($("#selectitem").text()=="" || $("#selectitem").val()==""){
        $.Huimodalalert("请选择项目！",2000);
        return false;
    }
    if(orderaccountarr==""){
        $.Huimodalalert("请选择下单账号！",2000);
        return false;
    }
    var approveAccountDtos={};
    var approveAccountDtosarr=[];
    var approvalli=$("#menu li");
    var accountnumber=$(".accountnumber2");
    var approvalinput=$(".approvalinput");
    var serialnumber=$(".serialnumber");
    var motyval=$(".motyval");
    var approveSeq="";
    var isApprove="";
    var count=0;//定义一个计数变量
    var settleTypedt='';
    $(".webselment").each(function(i,item){
        if($(item).is(':checked')==true){
            settleTypedt=$(item).val();
        }
    })

    for (let i=0;i<approvalli.length;i++) {
        if($(serialnumber[i]).is(':checked')==false){
            count++;
        }
    }
    //判断是否有审批顺序
    for (let i=0;i<approvalli.length;i++) {
        if($(approvalinput[i]).val()==undefined){
            approveSeq="0"
        }else {
            approveSeq=$(approvalinput[i]).val()
        }
        if($(motyval[i]).val()==undefined){
            ordrMoneyimit=""
        }else {
            ordrMoneyimit=$(motyval[i]).val()
        }
        console.log($(approvalinput[i]).val())
        if($(approvalinput[i]).val()==""){
            $.Huimodalalert("请填写审批顺序！",2000);
            return false;
        }
        //把审核顺序建立在一个新的llmap数组里
        llmap.push( Number($(approvalinput[i]).val()))

        //判断是否必须审批，全选传20，全不选传20，单个选择true传20；false传10
        if($(serialnumber[i]).is(':checked')==true){
            isApprove="20"

        }else {
            if($(".approval-orderxu").html() == '--'){
                isApprove = '20' 
            }else{
                if(count==$(serialnumber).length){//如果被没选中的个数等于$(serialnumber)的长度
                    isApprove="10"
                }else {
                    isApprove="10"
                }
            }

        }
        //审批账号数组
        approveAccountDtos={
            "memberId":$(accountnumber[i]).html(),
            "approveSeq":approveSeq,
            "isApprove":isApprove,
            "isOrSign":isOrSigndt,
            "orderMoneyLimit":ordrMoneyimit,
        }
        approveAccountDtosarr.push(approveAccountDtos)
    }
    //判断审核顺序是否重复
              for(let i = 0;i<llmap.length;i++){
              if(newarr.indexOf(llmap[i]) == -1){
                  newarr.push(llmap[i]);
              }else{
                  countnew.push(llmap[i]);
              }
          }
          if(countnew.length>0){
              countnew=[];
              $.Huimodalalert("审核顺序不可重复！",2000);
              return false;
          }
          //判断空值
console.log(approveAccountDtosarr)
    if(approveAccountDtosarr==""){
       $.Huimodalalert("请选择审批账号！",2000);
        return false;
    }
    if(settlementaccountarr==""){
        $.Huimodalalert("请选择结算账号！",2000);
        return false;
    }
    if(isIng){
        $.Huimodalalert("请求已提交，请勿重复点击！",2000);
        return false;
    }
    isIng = true;
    settlementaccount.settleType=settleTypedt;
    $.ajax({
        url:root.member.saveBindRelation,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "customerId":$("#selectitem").text(),
            "orderAccountDto":orderaccount,//下单对象
            "approveAccountDtos":approveAccountDtosarr,//审核对象
            "settleAccountDto":settlementaccount,//结算对象
        }),
        success: function (data) {
            if (data.errorCode==0){
                $.Huimodalalert("创建成功！",5000);
                //置空
                $("#selectitem").val("")
                $("#selectitem").text("")
                $("#orderaccountadd").html("")
                $(".approvalaccounts").html("")
                $("#settlementaccount").html("")
                 orderaccountarr=[]//下单账号
                settlementaccountarr=[]//结算账号
                 approvalaccountarr=[]//审批账号
                accountmemberId=[]
                xuanzhongaccount=[]
                $("#organization_name").val("")
                $("#organization_name").text("")
                $("#adds").removeClass("add2-one")
                $("#deletes").removeClass("delete2-one")
                $("#adds").addClass("add-one")
                $("#deletes").addClass("delete-one")
                $("#adds").attr("onclick","orderaccountadd(1)")
                $("#deletes").removeAttr("onclick");

                $("#adds2").removeClass("add2-one")
                $("#deletes2").removeClass("delete2-one")
                $("#adds2").addClass("add-one")
                $("#deletes2").addClass("delete-one")
                $("#adds2").attr("onclick","orderaccountadd(2)")
                $("#deletes2").removeAttr("onclick");

                $("#adds3").removeClass("add2-one")
                $("#deletes3").removeClass("delete2-one")
                $("#adds3").addClass("add-one")
                $("#deletes3").addClass("delete-one")
                $("#adds3").attr("onclick","orderaccountadd(3)")
                $("#deletes3").removeAttr("onclick");
                $("#civil").prop("checked",false);
                $("#huoqian").prop("checked",false);
                $(".webselmentq").prop("checked",true);
                approvalorders=0
                isIng = false;
            } else {

                $.Huimodalalert(data.msg,2000);
                isIng = false;
            }

        },
        error: function () {

            $.Huimodalalert('失败！',2000);
            isIng = false;

        }
    });
}




/*-------------------------------------------------------------华丽丽的分割线-----------------------------------------------------------------------------*/


//账号关系表
//点击显示隐藏二级品类
var suma="0"

//查询列表
function accountrelationship() {
    $.ajax({
        contentType: 'application/json',
        url: root.member.memberRelationship,
        cache: false,  //禁用缓存
        type: "POST",
        data: JSON.stringify({
            "mainCustomerId":mainCustomerId,
            "customerName":$("#customerName").val(),
            "orderAccount": $("#orderAccount").val(),
            "athorAccount": $("#athorAccount").val(),
            "settlementAccount": $("#settlementAccount2").val(),
        }),
        success: function (data) {
            if(data.errorCode==0) {
                var tableml=""
                var sort=""
                var sort2=""
                var mustAuth=""
                var mustAuth2=""
                var orderAccountUser=""
                var authorAccountUser=""
                var settlementAccountUser=""
                var authorAccountUser2=""
                var orderAccount1=""//下单账号
                var authorAccount1=""
                var settlementAccount1=""
                var level1List = data.data;
                if(level1List!=""){


                for (var i = 0; i < level1List.length; i++) {
                    var tableml2=level1List[i].subLines
                    //序号
                    if(level1List[i].sort==0){
                        sort="否"
                    }else {
                        sort=level1List[i].sort
                    }
                    //审核
                    if(level1List[i].mustAuth==null){
                        mustAuth=""
                    }else {
                        if(level1List[i].mustAuth==false){

                            mustAuth="否"
                        }else {
                            mustAuth="是"
                        }
                    }


                    //下单使用人
                    if(level1List[i].orderAccountUser==" "||level1List[i].orderAccountUser==""||level1List[i].orderAccountUser==null){
                        orderAccountUser="无"
                    }else {
                        orderAccountUser=level1List[i].orderAccountUser
                    }
                    //审批使用人
                    if(level1List[i].authorAccountUser==" "||level1List[i].authorAccountUser==""||level1List[i].authorAccountUser==null){
                        authorAccountUser="无"
                    }else {
                        authorAccountUser=level1List[i].authorAccountUser
                    }
                    //结算使用人
                    if(level1List[i].settlementAccountUser==" "||level1List[i].settlementAccountUser==""||level1List[i].settlementAccountUser==null){
                        settlementAccountUser="无"
                    }else {
                        settlementAccountUser=level1List[i].settlementAccountUser
                    }
                    //下单账号
                    if(level1List[i].orderAccount==" "||level1List[i].orderAccount==""||level1List[i].orderAccount==null){
                        orderAccount1="无"
                    }else {
                        orderAccount1=level1List[i].orderAccount
                    }
                    //审批账号
                    if(level1List[i].authorAccount==" "||level1List[i].authorAccount==""||level1List[i].authorAccount==null){
                        authorAccount1="无"
                    }else {
                        authorAccount1=level1List[i].authorAccount
                    }
                    //结算账号
                    if(level1List[i].settlementAccount==" "||level1List[i].settlementAccount==""||level1List[i].settlementAccount==null){
                        settlementAccount1="无"
                    }else {
                        settlementAccount1=level1List[i].settlementAccount
                    }
                    if(tableml2!=""&&tableml2!=null) {
                    tableml+='<tr >'
                    tableml+='<td style="text-align: left"><i class="drop-down" onclick="level2_show(this,'+level1List[i].accountRelationId+')"><input style="display: none" value="1"></i>'+level1List[i].customerName+'</td>';
                    tableml+='<td>'+orderAccount1+'</td>';
                    tableml+='<td>'+orderAccountUser+'</td>' ;
                    tableml+='<td>'+authorAccount1+'</td>' ;
                    tableml+='<td>'+authorAccountUser+'</td>' ;
                    if(level1List[i].isOrSign == 1){
                        tableml+='<td>是</td>' ;
                    }else{
                        tableml+='<td>否</td>' ;
                    }
                    tableml+='<td>'+sort+'</td>' ;
                    if( mustAuth=="否" && level1List[i].isOrSign == 0 ){
                        tableml+='<td>否</td>' ;
                        tableml+='<td>否</td>' ;
                    }else{
                        tableml+='<td>'+mustAuth+'</td>' ;
                        if(level1List[i].orderMoneyLimit !="" && level1List[i].orderMoneyLimit >0){
                            tableml+='<td>订单金额<'+level1List[i].orderMoneyLimit+',跳过本级审批</td>' ;
                        }else{
                            tableml+='<td>否</td>' ; 
                        }
                      
                    }

                    tableml+='<td>'+settlementAccount1+'</td>' ;
                    tableml+='<td>'+settlementAccountUser+'</td>';
                    tableml+='<th>' ;
                    tableml+='<div class="reliev-ation">' ;
                    tableml+= '<a class="" onclick="relievingassociation(\'' +level1List[i].accountRelationId + '\')">解除关联</a>&nbsp;' ;
                    tableml+= '<a class="modify" onclick="relievingupdata(\'修改账号关联\',\'modifyaccount.html\',\'' +level1List[i].accountRelationId + '\')">修改</a>' ;
                    tableml+= ' </div>' ;
                    tableml+= '</th>' ;
                    tableml+=' </tr>' ;
                        for (var j = 0; j < tableml2.length; j++) {
                            console.log(tableml2.length)
                            //序号
                            if(tableml2[j].sort==0){
                                sort2="否"
                            }else {
                                sort2=tableml2[j].sort
                            }
                            //审核
                           if(tableml2[j].mustAuth==null){
                                mustAuth2=""
                            }else {
                               if(tableml2[j].mustAuth==false){

                                   mustAuth2="否"
                               }else {
                                   mustAuth2="是"
                               }
                            }

                            //审批使用人
                            if(tableml2[j].authorAccountUser==""||tableml2[j].authorAccountUser==null){
                                authorAccountUser2="无"
                            }else {
                                authorAccountUser2=tableml2[j].authorAccountUser
                            }
                            tableml += '<tr  class="okb'+tableml2[j].accountRelationId+'" style="display: none">';
                            tableml += '<td></td>';
                            tableml += '<td></td>';
                            tableml += '<td></td>';
                            tableml += '<td>' + tableml2[j].authorAccount + '</td>';
                            tableml += '<td>' + authorAccountUser2 + '</td>';
                            if(level1List[i].isOrSign == 1){
                                tableml+='<td>是</td>' ;
                            }else{
                                tableml+='<td>否</td>' ;
                            }
                            tableml += '<td>' + sort2 + '</td>';
                            
                            if( mustAuth2=="否" && level1List[i].isOrSign == 0 ){
                                tableml+='<td>否</td>' ;
                                tableml+='<td>否</td>' ;
                            }else{
                                tableml += '<td>' + mustAuth2 + '</td>';
                                if(tableml2[j].orderMoneyLimit !="" && tableml2[j].orderMoneyLimit >0){
                                    tableml+='<td>订单金额<'+tableml2[j].orderMoneyLimit+',跳过本级审批</td>' ;
                                }else{
                                    tableml+='<td>否</td>' ; 
                                  
                                }
                            }
                            tableml += '</tr>';
                        }
                    }else {
                        tableml+='<tr >'
                        tableml+='<td style="text-align: left"><i class="drop-down2"></i><input style="display: none" value="1"></i>'+level1List[i].customerName+'</td>';
                        tableml+='<td>'+orderAccount1+'</td>' ;
                        tableml+='<td>'+orderAccountUser+'</td>' ;
                        tableml+='<td>'+authorAccount1+'</td>' ;
                        tableml+='<td>'+authorAccountUser+'</td>' ;
                        if(level1List[i].isOrSign == 1){
                            tableml+='<td>是</td>' ;
                        }else{
                            tableml+='<td>否</td>' ;
                        }
                        
                        tableml+='<td>'+sort+'</td>' ;
                        if( mustAuth=="否" &&level1List[i].isOrSign == 0 ){
                            tableml+='<td>否</td>' ;
                            tableml+='<td>否</td>' ;
                        }else{
                            tableml+='<td>'+mustAuth+'</td>' ;
                            if(level1List[i].orderMoneyLimit !="" && level1List[i].orderMoneyLimit >0){
                                tableml+='<td>订单金额<'+level1List[i].orderMoneyLimit+',跳过本级审批</td>' ;
                            }else{
                                tableml+='<td>否</td>' ; 
                            }
                        }
                        tableml+='<td>'+settlementAccount1+'</td>' ;
                        tableml+='<td>'+settlementAccountUser+'</td>';
                        tableml+='<th>' ;
                        tableml+='<div class="reliev-ation">' ;
                        tableml+= '<a class="" onclick="relievingassociation(\'' +level1List[i].accountRelationId + '\')">解除关联</a>&nbsp;' ;
                        tableml+= '<a class="modify" onclick="relievingupdata(\'修改账号关联\',\'modifyaccount.html\',\'' +level1List[i].accountRelationId + '\')">修改</a>' ;
                        tableml+= ' </div>' ;
                        tableml+= '</th>' ;
                        tableml+=' </tr>' ;
                    }

            }
                $(".addpage-tbody").html(tableml)
                }else {
                    $(".addpage-tbody").html('<td valign="top" colspan="10" class="dataTables_empty">没有数据</td>')
                }
        }
        }
    });
}

function level2_show(e,id){
    if($(e).parent().find('input').val()==1){
        console.log()
        $(e).parents(".addpage-tbody").find(".okb"+id).show()//展示子级
        $(e).removeAttr("class");
        $(e).addClass("retract-down");
        $(e).parents(".level1").find(".plastyu").addClass("style-one")
        $(e).parent().find('input').val("2")
    }else {
        $(e).parents(".addpage-tbody").find(".okb"+id).hide()//隐藏子级
        $(e).removeAttr("class");
        $(e).parents(".level1").find(".plastyu").removeClass("style-one")
        $(e).addClass("drop-down");
        $(e).parent().find('input').val("1")
    }
}

//解除关联
function relievingassociation(id) {
    var curInd = layer.confirm(
        '<span>解除关联后，未完成订单不可操作，确定要解除关联吗?</span>'+'<br/>', {title:'提示',btn: ['解除', '取消']}, function(index){

            $.ajax({
                url:root.member.deleteBindRelation,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                data:{
                    "accountRelationId":id,
                },
                success: function (data) {
                    if(data.errorCode==0){
                        $.Huimodalalert('解除成功！',2000);
                        accountrelationship()
                    }else {
                        showMsg(5, data.msg);
                    }
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });
            layer.close(curInd);

        },function(){
            layer.close(curInd);

        });
}
//修改
function relievingupdata(title, url,id) {
    sessionStorage.setItem("accountRelationId",id)
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
/*-------------------------------------------------------------华丽丽的分割线-----------------------------------------------------------------------------*/
//关联项目
//客户归属
function myFunction(){
    var user_data = {
        "pageNum":1,

        "pageSize":500,

    }
    var succCallBack = function (data, status, response) {
        console.log(data)
        if(data.errorCode=="0"){
            var jsonObj =data.group;
            $("#tuankk").html("");
            if(jsonObj==""){
                $("#tuankk").html("<li>无数据</li> ");
            }else {
                console.log(jsonObj)

                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += "<li class='dda' onclick='relation("+ jsonObj[i].id+",\""+jsonObj[i].organization_name+"\")' data-align=\"" + jsonObj[i].id + "\" > " + jsonObj[i].organization_name + "</li>";
                }
                $("#tuankk").html(optionstring);
                $(".kehus").animate({scrollTop:"0"},1);
                $("#tuankk").show()

            }
        }else{
            $("#tuankk").html("<li>无数据</li> ");
        }
    }
    /*root.member.getGroup*/
    web.doAjax(root.member.getGroup,'post',user_data, succCallBack);

}
/*//取光标
$("#organization_name").focus(function () {
    $("#tuank").show()
});*/
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuankk").length == 0 && $(e.target).closest("#organization_name2").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuankk").hide()
    }
})
function relation(id,ce) {
    $("#organization_name2").val(ce).text(id)
    $("#tuankk").hide()
}



function relateditems() {

    $.ajax({
        url:root.member.getCustomers,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":30,
            "customerCode":$("#customerCode").val(),
            "customerId":$("#customerId").val(),
            "customerName":$("#customerName2").val(),
            "mainCustomerId":mainCustomerId,
            "isOnlyFreeOfMain":"false",
            "belongGroupId": $("#organization_name2").text()
        }),
        success: function (data) {
            datas=data.data.data
            couponlist(data.data, 0);
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $("#spu_all").prop("d")
                    $.ajax({
                        url: root.member.getCustomers,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":30,
                            "customerCode":$("#customerCode").val(),
                            "customerId":$("#customerId").val(),
                            "customerName":$("#customerName2").val(),
                            "mainCustomerId":mainCustomerId,
                            "isOnlyFreeOfMain":"false",
                            "belongGroupId":$("#organization_name2").text()

                        }),
                        success: function (result) {
                            couponlist(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
dataSource = [];
function couponlist(data, index){
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data.data));
    dataSource.splice(0,dataSource.length);//清空数组
    if(data.data !=null && data.data != ''){
        var datashu =data.startRow+1;
        $.each(data.data, function (i, field) {
            var datashus = datashu++
            var rowData = new Array();
            rowData.push(field.customerCode);
            rowData.push(field.customerId);
            rowData.push(field.customerName);
            rowData.push(field.belongGroupName);
            rowData.push(datashus);
            dataSource.push(rowData);

        });
    }
    initDataTable(dataSource);
    function initDataTable(dataSource) {

        var dttable = $('#relateditemstable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#relateditemstable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = '<a onclick="detail(\'签约客户信息详情\',\'../tomer_see.html?id=' + row[0] +'&customerId=' + row[1] + '\')">详情信息</a><a style="margin-left:5px;" onclick="removes(\''+row[1]+ '\')">移除</a>'
                        return val;
                    },
                    "targets": 5
                },

            ],
        });
    };
}

function detail(title, url) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

//主客户限制字符
var len
var Preser
var common=100//要限制输入的字数
function checkMaxIut(me) {
    var text=$(me).val()
    strlen(text)
    if(len>common){
        $(me).val(Preser)
    }else {
        Preser=$(me).val()
    }
}
function strlen(str){
    len = 0;
    for (var i=0; i<str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
            len++;
        } else {
            len+=2;
        }
    }
    return len;
}

function showhdemoy(e){
    if($(e).is(':checked')){
        $(e).parent().next().removeClass('hide')
    }else{
        $(e).parent().next().addClass('hide')  
    }
};
//移除
function removes(id) {
    var curInd = layer.confirm(
        '<span>移除后账号体系将解除关联，确定移除吗？</span>'+'<br/>', {title:'提示',btn: ['确定', '取消']}, function(index){
            $.ajax({
                url:root.member.relationMainCustomer,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: JSON.stringify({
                    "manCustomerId":mainCustomerId,
                    "customerIds":id,
                    "removeRelation":"true",
                }),
                success: function (data) {
                    if(data.errorCode==0){
                        $.Huimodalalert("移除成功",2000);
                        relateditems()
                    }else {
                        $.Huimodalalert(data.msg,2000);
                    }
                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });
            layer.close(curInd);

        },function(){
            layer.close(curInd);

        });

};
//---------新增-----//
function customerjump(title, url) {
    sessionStorage.setItem("mainCustomerIds",mainCustomerId)
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
//跳转
function createanaccount(title,url) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

//获取主客户详细信息-puchOut
function mainCustomerInfo() {
    var param = { ids:mainCustomerId };
    console.log(param);
    $.ajax({
        url: root.member.mainCustomerInfo,
        cache: false, //禁用缓存
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data:JSON.stringify(param),
        success: function (data) {
            if(data.errorCode == 0){
             if(data.data){
                 //10 数采客户组；20 punchout数采平台审核； 30 punchout客户平台审核
                 switch (data.data.customerType) {
                     case 10:
                        $("#project-map-tab").hide();
                         break;
                     case 20:
                         if (!data.data.mainCustomerSettingsEntity || data.data.mainCustomerSettingsEntity.acceptProject == "20") {//对接项目 acceptProject:10：是 20：否 
                             $("#project-map-tab").hide();
                         }
                         break;
                     case 30:
                         
                         break;
                 
                     default:
                         break;
                 }
             }else{
                $.Huimodalalert("未查到客户组详情",2000);
             }
            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
      });
}

//客户组关系表导出
function exportAccountRelations()
{
    window.location.href = root.member.exportAccountRelations + "?mainCustomerId=" + mainCustomerId;
}

//账号池导出
function exportCustomerUser()
{
    window.location.href = root.member.exportCustomerUser + "?mainCustomerId=" + mainCustomerId;
}